import { createRouter, createWebHistory } from "vue-router";
import {
  Avatar,
  List,
  Goods,
  PieChart,
  Message,
  Setting,
} from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/userInfo";
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/dashboard",
    },
    {
      path: "/dashboard",
      name: "dashboard",
      component: () => import("../views/modules/Dashboard.vue"),
      meta: {
        title: "数据分析",
        icon: PieChart,
        isMenu: true,
        isAuth: true,
      },
    },
    {
      path: "/products",
      name: "products",
      component: () => import("../views/modules/Products.vue"),
      meta: {
        title: "商品管理",
        icon: Goods,
        isMenu: true,
        isAuth: true,
      },
    },
    {
      path: "/orders",
      name: "orders",
      component: () => import("../views/modules/Orders.vue"),
      meta: {
        title: "订单管理",
        icon: List,
        isMenu: true,
        isAuth: true,
      },
    },
    {
      path: "/users",
      name: "users",
      component: () => import("../views/modules/Users.vue"),
      meta: {
        title: "用户管理",
        icon: Avatar,
        isMenu: true,
        isAuth: true,
      },
    },
    {
      path: "/carousel",
      name: "carousel",
      component: () => import("../views/modules/Carousel.vue"),
      meta: {
        title: "轮播管理",
        icon: Setting,
        isMenu: true,
        isAuth: true,
      },
    },
    {
      path: "/notice",
      name: "notice",
      component: () => import("../views/modules/Notice.vue"),
      meta: {
        title: "公告管理",
        icon: Message,
        isMenu: true,
        isAuth: true,
      },
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/modules/Login.vue"),
    },
  ],
});

router.afterEach((to, from, next) => {
  window.scrollTo(0, 0);
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  if (to.meta.isAuth && !userStore.token) {
    next({ name: "login" });
  } else {
    next();
  }
});

export default router;
